package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏西西
 * Date: 2023-09-01
 * Time: 16:21
 */
//针对多个线程的执行控制
//三个线程分别只能打印A、B、C，写出代码，保证这三个线程按照固定的顺序来打印
    //思路：首先设置两个对象两把锁。第一把锁线程1和线程2使用，第二把锁给线程2和线程3使用

public class ThreadD18 {
    public static void main(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();

        //第一把锁先给线程1和线程2加上，线程2执行wait操作，在线程1进行notify后才可以继续执行线程2
        //第二把锁同理，线程3执行wait操作，线程2执行notify后再进线程3的执行。
        //综上所述我们要执行的顺序就是线程1-线程2-线程3
        Thread t1 = new Thread(() -> {
            System.out.println("A");
            try {
                synchronized (locker1) {
                    locker1.notify();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });
        Thread t2 = new Thread(() -> {
            try {
                synchronized (locker1) {
                    locker1.wait();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("B");
            synchronized (locker2) {
                locker2.notify();
            }

        });
        Thread t3 = new Thread(() -> {
            try {
                synchronized (locker2) {
                    locker2.wait();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("C");
        });


        t2.start();
        t3.start();
        //这里对程序进行休眠确保线程2和线程3可以先启动，进行wait操作，这样我们后续的notify操作才会顺利执行
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        t1.start();
    }
}
